package databasetranslation;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import models.Client;
import models.Payment;
import database.SQLServer;

public class PaymentList extends DatabaseList<Payment> {
	private ClientList clients;
	
	/**
	 * constructor, create's a PaymentsList
	 * 
	 * @param server for the database communication
	 * @param clients list of clients for searching clients on client Id
	 */
	public PaymentList(SQLServer server, ClientList clients) {
		super(server, "paymentlist");
		this.clients = clients;	
	}

	/**
	 * Makes a list of payments from the given client.
	 * @param client
	 * @return a List of the payments from the given client. (warning payments are not copies)
	 */
	public List<Payment> getPaymentsOf(Client client) {
		List<Payment> payments = new ArrayList<Payment>();
		for (Payment payment: getEntries()) {
			if (payment.getClient() == client) {
				payments.add(payment);
			}
		}
		return payments;
	}
	
	/**
	 * Sums the payments of client.
	 * @param client
	 * @return a double Sum of the payments in the list.
	 */
	public double getPaymentsTotal(Client client) {
		double total = 0;
		for (Payment payment: getPaymentsOf(client)) {
			total += payment.getAmount();
		}
		return total;
	}
	
	/**
	 * Create a copy of the List of payments.
	 * @return List of Payments
	 */
	public List<Payment> getPayments() {
		return new ArrayList<Payment>(getEntries());
	}
	
	/**
	 * Create a Payment from the current selected ResultSet row
	 * 
	 * @param rs ResultSet with a selected row of a Payment
	 * @return the Payment created from the ResultSet
	 */
	@Override
	public Payment convertResultSetToModel(ResultSet rs) throws SQLException {
		Client paymentClient = clients.getEntry(rs.getInt("client"));
		return new Payment(rs.getInt("id"),paymentClient, rs.getDouble("amount"), rs.getDate("date"), rs.getString("comment"));
	}

}
